import axios from 'axios';
import notification from 'ant-design-vue/es/notification';
import { useUserStore } from '@/store';
import { ACCESS_TOKEN } from '@/store/user';
import { download } from './download';
import { RESPONSE_CODE } from '@/constants';

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  timeout: 20000, // 请求超时时间
});

/**
 * @desc: 异常拦截处理器
 * @param { Object } error 错误信息
 */
const errorHandler = (error: any) => {
  const { status, data } = error.response;
  // 超出 2xx 范围的状态码都会触发该函数。

  if (data.code === RESPONSE_CODE.FAILURE) {
    notification.error({ message: data.msg, description: data.data });
  } else {
    switch (status) {
      case 403:
        notification.error({ message: 'Forbidden', description: data.message });
        break;
      case 401: {
        notification.error({
          message: 'Unauthorized',
          description: 'Authorization verification failed',
        });
        const token = sessionStorage.getItem(ACCESS_TOKEN);
        if (token) {
          const userStore = useUserStore();
          userStore.clearState();
          setTimeout(() => (window.location.href = '/'), 1500);
        }
        break;
      }
      default:
        console.log('🚀 ~ errorHandler ~ error:', error);
        notification.error({ message: error.message, description: data });
        break;
    }
  }

  return Promise.reject(error);
};

// request interceptor
request.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token');
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use(response => {
  const { status, data, headers } = response;
  if (status === 200) {
    // content-disposition: "attachment;filename=%E7%B3%BB%E7%BB%9F%E7%94%A8%E6%88%B7.xlsx"
    // content-type: "application/octet-stream;charset=UTF-8"
    const contentDisposition = headers['content-disposition'];
    const contentType = headers['content-type'];
    if (contentDisposition?.includes('attachment')) {
      const startIndex = contentDisposition.indexOf('=') + 1;
      const filename = decodeURIComponent(contentDisposition.slice(startIndex));
      download(data, contentType, filename);
      return;
    }

    if (data.code === RESPONSE_CODE.SUCCESS) {
      return data;
    } else if (data.code === RESPONSE_CODE.FAILURE) {
      notification.error({ message: data.msg, description: data.data });
      // } else if (data.code === RESPONSE_CODE.LOGIN_EXPIRATION) {
      //   // 登录已过期
      //   message.error(data.message);
      //   userStore.clearState();
      //   router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } });
      //   return Promise.reject(response);
    } else {
      notification.error(data.message);
      return Promise.reject(data);
    }
  } else {
    return Promise.reject(response);
  }
}, errorHandler);

export default request;

export { request as axios };
